/**
 * 与widget的router.open方法一样，只是要默认statusBarStyle为LightContent
 */

import routes from './routes'
import { isUndefined, isFunction} from '../plugins/utils'

const router = weex.requireModule('bmRouter')
const modal = weex.requireModule('bmModal')
const getUrl = page => {
  const currentPageInfo = routes[page]
  if (!currentPageInfo) {
    modal.alert({ message: '跳转页面不存在', okTitle: '确定' })
    return false
  }
  return currentPageInfo
}

const Nav = Object.create(null)
Nav.install = Vue => {
  Vue.prototype.$nav = {
    open: (options = {}) => {
      const currentPageInfo = getUrl(options.name)
      if (!currentPageInfo || !currentPageInfo.url) return
      return new Promise((resolve, reject) => {
        const isRunBack = isFunction(options.backCallback)
        router.open({
          url: currentPageInfo.url,
          type: options.type || 'PUSH',
          params: options.params || {},
          canBack: isUndefined(options.canBack) || options.canBack,
          gesBack: isUndefined(options.gesBack) || options.gesBack,
          navShow: options.navShow || !!currentPageInfo.title,
          navTitle: options.navTitle || currentPageInfo.title,
          isRunBackCallback: isRunBack,
          statusBarStyle: options.statusBarStyle || 'LightContent'
        }, data => {
          if (isRunBack) { options.backCallback.call(this, data) }
        })
      })
    }
  }
}

Vue.use(Nav)
